#!/usr/bin/env python3
# -*- coding: utf-8 -*-

"""
retriever service
"""
import json

from src.common.singleton import singleton
from src.common.log import logger
from src.common.error import Code, Error
from src.common.time import cal_time
from src.service.dto.agent import AgentServiceParams, AgentServiceResult

from csagent.core.builder.agent_builder import AgentBuilder

@singleton
class AgentService(object):
    """ agent service """
    def __init__(self, agent_yaml: str):
        self.agent = AgentBuilder.from_yaml(agent_yaml)
    
    def run(self, params: dict):
        logger.info(f"agent service params:{json.dumps(params, ensure_ascii=False)}")
        stream = params.get('stream', False)
        if stream:
            return self.run_stream(params)
        results = list(self.run_stream(params))
        if not results:
            return AgentServiceResult(
                code=2000, err_msg='agent执行异常',user_id=params.get('user_id',''),
                session_id=params.get('session_id',''), log_id=params.get('log_id','')
            )
        final_res = results[-1]
        return final_res
    
    def run_stream(self, params: dict):
        # 做一层转换, 可以根据需要增加一些输入校验
        input_data = AgentServiceParams(**params)
        for item in self.agent.run(input_data.model_dump(), True):
            # 业务todo: 需要根据实际业务场景过滤掉一些不必要的返回，比如如果是智能问答的场景
            # 需要根据意图过滤掉最后的非增量结果
            # if 意图==健康问答 and not item['is_delta']:
            # continue 
            yield AgentServiceResult(**item)




